/**
 * desc：
 * author：王文军
 * date：  2024/7/9 09:28
 */
'use strict';
const { execSync } = require('child_process');
const fs = require('fs');
const readline = require('readline');

// 执行指令
function runCommand(command) {
  try {
    const result = execSync(command, { stdio: 'pipe' }); // 使用 pipe 模式，以便处理空输出
    return result.toString().trim(); // 转换结果为字符串并去除首尾空白
  } catch (error) {
    console.error(`指令执行错误 command '${command}': ${error.message}`);
    process.exit(1);
  }
}

// prompt命令行交互
function prompt(question) {
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  return new Promise((resolve) => {
    rl.question(question, (answer) => {
      rl.close();
      resolve(answer);
    });
  });
}

async function main() {
  // 1: 只能是mater分支才能执行
  const currentBranch = runCommand('git branch --show-current').trim();
  if (currentBranch !== 'master') {
    console.error('Error: This script can only be run from the master branch.');
    process.exit(1);
  }

  // 2: 更新package.json version 跟 description
  const packageJsonPath = './package.json';
  let packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));

  const newVersion = await prompt('Enter new version: ');
  const newDescription = await prompt('Enter new description: ');

  packageJson.version = newVersion;
  packageJson.description = newDescription;

  fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));

  // 3: 选择 Git commit template
  const commitType = await prompt('Choose commit type (feat, fix, docs, build, revert, etc.): '); // commit complate
  const commitScope = await prompt('Enter commit scope change: '); // commit 文件修改范围
  const commitMessage = await prompt('Enter commit message: ');

  runCommand(`git commit -am "${commitType}(${commitScope}): ${commitMessage}"`);

  // 4: Git push
  runCommand('git push origin master');

  // 5: Git tag
  const latestCommitHash = runCommand('git log -1 --pretty=format:"%H"');
  const tagVersion = await prompt('Enter tag version: ');
  const tagMessage = await prompt('Enter tag message: ');

  runCommand(`git tag -a ${tagVersion} -m "${tagMessage}" ${latestCommitHash}`);

  // 6: Git tag push
  runCommand(`git push origin ${tagVersion}`);

  console.log('版本上线成功！！！');
}

main();
